package com.sunwayworld.dev.core.generate;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import com.sunwayworld.dev.core.valueobject.JavaObject;
import com.sunwayworld.dev.io.freemarker.GenerateUtils;
import com.sunwayworld.dev.util.DevConfigUtil;
import com.sunwayworld.dev.util.StringDevUtil;

public class GenerateEJB2XML {
	private JavaObject javaObject;

	private String[] srcPaths = new String[3];

	private String[] vmPaths = new String[3];

	private Map context = new HashMap();

	public GenerateEJB2XML(String vmPath, String packageName, String tableName) {
		String[] vms = { "/ejb-jar.xml.vm", "/weblogic-cmp-rdbms-jar.xml.vm",
				"/weblogic-ejb-jar.xml.vm" };

		String baseSrc = DevConfigUtil.getProperty("src");

		vmPaths[0] = vmPath + vms[0];
		vmPaths[1] = vmPath + vms[1];
		vmPaths[2] = vmPath + vms[2];

		srcPaths[0] = StringDevUtil.getSrcFilePath(baseSrc, packageName
				+ ".META-INF." + tableName, "ejb-jar.xml");
		srcPaths[1] = StringDevUtil.getSrcFilePath(baseSrc, packageName
				+ ".META-INF." + tableName, "weblogic-cmp-rdbms-jar.xml");
		srcPaths[2] = StringDevUtil.getSrcFilePath(baseSrc, packageName
				+ ".META-INF." + tableName, "weblogic-ejb-jar.xml");
	}

	@SuppressWarnings("unchecked")
	public void putContext(String key, Object obj) {
		context.put(key, obj);
	}

	public void generateCode() {
		try {
			for (int i = 0; i < vmPaths.length; i++) {
				GenerateUtils gf = new GenerateUtils();

				copyProperties(javaObject, context);
				gf.generate(vmPaths[i], srcPaths[i], context);
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@SuppressWarnings("unchecked")
	private void copyProperties(Object provide, Map context) {

		if (provide == null || context == null)
			return;
		Field[] fields = provide.getClass().getFields();
		for (int i = 0; i < fields.length; i++) {
			String fieldName = fields[i].getName();

			try {
				Object temp = fields[i].get(provide);
				if (temp != null) {
					context.put(fieldName, temp);
				}
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}
}
